Missing Ranges

Given a sorted integer array where the range of elements are [lower, upper] inclusive, return its missing ranges.

For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].

Solution:

  1. public class Solution {
  2. public List<String> findMissingRanges(int[] a, int lo, int hi) {
  3. List<String> res = new ArrayList<String>();
  4. // the next number we need to find
  5. int next = lo;
  6. for (int i = 0; i < a.length; i++) {
  7. // not within the range yet
  8. if (a[i] < next) continue;
  9. // continue to find the next one
  10. if (a[i] == next) {
  11. next++;
  12. continue;
  13. }
  14. // get the missing range string format
  15. res.add(getRange(next, a[i] - 1));
  16. // now we need to find the next number
  17. next = a[i] + 1;
  18. }
  19. // do a final check
  20. if (next <= hi) res.add(getRange(next, hi));
  21. return res;
  22. }
  23. String getRange(int n1, int n2) {
  24. return (n1 == n2) ? String.valueOf(n1) : String.format("%d->%d", n1, n2);
  25. }
  26. }